<template>
	<el-drawer class="detail-drawer" v-model="drawerVisible" append-to-body destroy-on-close :title="title" :size="size">
		<div v-loading="loading">
			<CardDescriptions
				class="card-descriptions"
				v-for="(group, index) in groupList"
				:key="index"
				:title="group.title"
				:data="initData"
				:metadata="group.metadata"
			>
				<!-- 递归传递非当前页面的插槽！！！ -->
				<template v-for="slotName in Object.keys($slots)" #[slotName]="scope">
					<!-- <slot :name="slotName" v-bind="scope" /> -->
					<slot v-if="!selfSlots.has(slotName)" :name="slotName" v-bind="scope" />
				</template>
				<!-- 默认插槽 -->
				<slot v-if="group.slotName" :name="group.slotName" v-bind="{ group, data: initData }"> </slot>
				<template #header_right>
					<slot v-if="group.slotName" :name="genHeaderRightSlot(group.slotName)" v-bind="{ group, data: initData }"> </slot>
				</template>
			</CardDescriptions>
		</div>

		<template #footer v-if="$slots.footer">
			<slot name="footer" v-bind="{ data: initData }"></slot>
		</template>
	</el-drawer>
</template>

<script setup lang="ts" name="DetailDrawer">
import { ref, toRaw } from 'vue'
import { DetailGroupProps } from './interface'
import CardDescriptions from '@/components/CardDescriptions/index.vue'
import { deepClone } from '@/utils/util'
interface DrawerProps {
	title?: string // 标题
	size?: string | number // Drawer 窗体的大小
	/*  */
	groupList: DetailGroupProps[] // 配置项目列表
}
// 默认值
const props = withDefaults(defineProps<DrawerProps>(), {
	title: '详情'
})
// 当前组件的插槽
const selfSlots: Set<string> = new Set(['footer'])
for (const group of props.groupList) {
	if (group.slotName) {
		selfSlots.add(group.slotName)
		selfSlots.add(genHeaderRightSlot(group.slotName))
	}
}
// 生成 heanderRight 的插槽
function genHeaderRightSlot(slotName: string): string {
	return `${slotName}_header_right`
}

// drawer框状态
const drawerVisible = ref(false)
// 加载
const loading = ref(false)
const initData = ref<Record<string, any>>({})

/**
 * 打开，并根据参数初始化表单
 * @param data 初始表单的数据
 */
function openDataInit(data: Record<string, any> = {}): void {
	initData.value = deepClone(toRaw(data))
	drawerVisible.value = true
}

/**
 * 打开，并提供初始化接口
 * @param apiInit apiInit 接口
 */
function openApiInit(apiInit: Promise<Record<string, any>>): void {
	loading.value = true
	apiInit
		.then(data => {
			initData.value = data
		})
		.finally(() => {
			loading.value = false
		})
	drawerVisible.value = true
}
/**
 * 弹框关闭
 * @param val
 */
function close() {
	drawerVisible.value = false
}
defineExpose({ openDataInit, openApiInit, close })
</script>
<style lang="scss" scoped>
.card-descriptions {
	margin-bottom: 20px;
}
</style>
